package com.test.redis_demo.service;

import com.alibaba.fastjson.JSONObject;
import com.test.redis_demo.dao.UserDao;
import com.test.redis_demo.model.User;
import com.test.redis_demo.util.CookieUtil;
import com.test.redis_demo.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;

@Service
public class UserService {
    @Autowired
    UserDao userDao;
    @Autowired
    RedisService redisService;
    public User findUserByUserName(String userName){
        User user = (User) redisService.getVal(userName);
        if (user != null){
            return user;
        }
        user = userDao.getUserByName(userName);
        if (user != null){
            redisService.setVal(userName,user);
        }
        return user;
    }

    public JSONObject userLogin(HttpServletResponse response, String userName, String passWord){
        JSONObject json = new JSONObject();
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(passWord)){
            json.put("status",false);
            json.put("msg","账号或密码不可为空");
            return json;
        }
        User user = findUserByUserName(userName);
        if (user == null){
            json.put("status",false);
            json.put("msg","输入正确的登录信息");
            return json;
        }
        if (passWord.equals(user.getPasw())){
            String token = UUIDUtil.uuid();
            redisService.setVal(token,user);
            CookieUtil.setCookie(response,token);
            json.put("status",false);
        }
        return json;
    }

    public User getUserByToken(HttpServletResponse response, String token) {
        if (StringUtils.isEmpty(token)){
            return null;
        }
        User user = (User) redisService.getVal(token);
        if (user != null){
            CookieUtil.setCookie(response,token);
        }
        return user;
    }
}
